/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

CppSharedLibraryNode::CppSharedLibraryNode(
	BuildGraph* graph,
	vector<CppSourceNode*> sources,
	CppToolchain* toolchain,
	CppCompileFlagList cflags,
	CppLinkFlagList lflags,
	string name)
	: CppExecutableNode(graph, sources, toolchain, cflags, lflags, name)
	, m_hidden(false)
{
}

CppSharedLibraryNode::~CppSharedLibraryNode()
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Compilation

string CppSharedLibraryNode::GetOutputPath()
{
	string prefix = m_graph->GetOutDir() + "/" + m_toolchain->GetArchitecture() + "/";
	if(m_hidden)
		return prefix + ".lib" + m_name + m_toolchain->GetSharedLibrarySuffix();
	else
		return prefix + "lib" + m_name + m_toolchain->GetSharedLibrarySuffix();
}

string CppSharedLibraryNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "C++ shared library %s [%s]", m_name.c_str(), m_toolchain->GetArchitecture().c_str());
	return string(desc);
}

string CppSharedLibraryNode::GetBinaryPath()
{
	return m_graph->GetMetaDir() + "/" + GetHashCached()  + "/lib" + m_name + ".so";
}

void CppSharedLibraryNode::Update(Cluster* cluster)
{
	string buildbase = "lib" + m_name + ".so";
	string outdir   = m_graph->GetMetaDir() + "/" + GetHashCached();
	string binpath  = outdir  + "/" + buildbase;
	
	//Rebuild all of our dependencies if necessary
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{		
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}		
	
	//Save object file names
	vector<string> objects;
	for(size_t i=0; i<m_objects.size(); i++)
		objects.push_back(m_objects[i]->GetOutputPath());
		
	//Dispatch the link command
	m_job = m_toolchain->LinkObjectsToSharedLibrary(
		objects,
		binpath,
		m_lflags,
		deps,
		cluster);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

CppSharedLibraryNode* CppSharedLibraryNode::CreateCppSharedLibraryNode(
	BuildGraph* graph,
	std::vector<std::string> sources,
	CppToolchain* toolchain,
	CppCompileFlagList cflags,
	CppLinkFlagList lflags,
	std::string name,
	bool target)
{
	//Set up flags (position independent is mandatory)
	cflags.push_back(new CppPositionIndependentCodeFlag);

	string arch = toolchain->GetArchitecture();

	//Create source and object nodes for each of the source files
	vector<CppSourceNode*> sourcenodes;
	for(size_t i=0; i<sources.size(); i++)
	{	
		//Add the new source node if it doesn't already exist in the graph
		CppSourceNode* srcnode = NULL; 
		if(NULL == (srcnode = dynamic_cast<CppSourceNode*>(graph->GetNodeForPath(sources[i], arch))))
		{
			srcnode = new CppSourceNode(graph, sources[i], arch);
			graph->AddNodeWithPath(srcnode, sources[i], arch);
		}
		sourcenodes.push_back(srcnode);
	}
	
	//Add the executable node
	CppSharedLibraryNode* libnode = new CppSharedLibraryNode(graph, sourcenodes, toolchain, cflags, lflags, name);
	graph->AddNodeWithPath(libnode, libnode->GetOutputPath(), arch);
	
	//Add it as a top-level target if requested
	if(target)
		graph->AddTarget(libnode, libnode->GetTargetName());
	
	//Done
	return libnode;
}
